package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code49LowestCommonAncestorOfABinaryTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // 当前节点是 null 或者是 p 或者是 q
        if (root == null || root == p || root == q) {
            return root;
        }
        // 去左右子树找 p 和 q
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        // 左右子树都找不到
        if (left == null && right == null) {
            return null;
        }
        // 左子树找不到, 右子树找到了
        if (left == null) {
            return right;
        }
        // 右子树找不到, 左子树找到了
        if (right == null) {
            return left;
        }
        // 左右子树都找到了, 当前节点就是最近公共祖先
        return root;
    }
}
